using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace extend_360.utils
{
    public class VPNConnectionUtils
    {
        /*// RasDial API
        [DllImport("rasapi32.dll", CharSet = CharSet.Auto)]
        private static extern int RasDial(
            ref RASDIALPARAMS lpRasDialParams,
            string lpszPhoneBook,
            ref RASDIALEXTENSIONS lpRasDialExtensions,
            IntPtr lpvNotifier,
            ref IntPtr lphRasConn
        );

        // RasHangUp API
        [DllImport("rasapi32.dll", CharSet = CharSet.Auto)]
        private static extern int RasHangUp(IntPtr hRasConn);

        // RASDIALPARAMS 结构体
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        private struct RASDIALPARAMS
        {
            public int dwSize;

            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 257)]
            public string szEntryName;

            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
            public string szPhoneNumber;

            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 129)]
            public string szCallbackNumber;

            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 129)]
            public string szUserName;

            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 129)]
            public string szPassword;

            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 129)]
            public string szDomain;
        }

        // RASDIALEXTENSIONS 结构体
        [StructLayout(LayoutKind.Sequential)]
        private struct RASDIALEXTENSIONS
        {
            public int dwSize;
            public int dwfOptions;
            public IntPtr hwndParent;
            public IntPtr reserved;
        }

        // 配置 VPN 连接
        // 配置 VPN 连接
        public static void ConfigureVPN(string connectionName, string serverAddress)
        {
            string command =
                $"Add-VpnConnection -Name \"{connectionName}\" -ServerAddress \"{serverAddress}\"  -TunnelType Automatic -RememberCredential -Force";
            RunPowerShellCommand(command);
        }
  // 连接 VPN
        public static bool Connect(string entryName, string username, string password,
            ref IntPtr rasConn)
        {
            RASDIALPARAMS dialParams = new RASDIALPARAMS();
            dialParams.dwSize = Marshal.SizeOf(typeof(RASDIALPARAMS));
            dialParams.szEntryName = entryName;
            dialParams.szUserName = username;
            dialParams.szPassword = password;
            dialParams.szDomain = ""; // 空字符串
            dialParams.szCallbackNumber = ""; // 空字符串
            dialParams.szPhoneNumber = ""; // 空字符串
            RASDIALEXTENSIONS dialExtensions = new RASDIALEXTENSIONS();
            dialExtensions.dwSize = Marshal.SizeOf(typeof(RASDIALEXTENSIONS));
            rasConn = IntPtr.Zero;
            int result = RasDial(ref dialParams, null, ref dialExtensions, IntPtr.Zero,
                ref rasConn);
            if (result != 0)
            {
                Console.WriteLine($"连接 VPN 失败，错误代码: {result}");
                return false;
            }

            return true;
        }

        // 断开 VPN 连接
        public static void Disconnect(IntPtr rasConn)
        {
            RasHangUp(rasConn);
        }*/
        /**
         * 连接VPN
         */
        public static void Connect(string entryName, String address, string username,
            string password)
        {
            /**
             * VPN名称是否存在 存在状态 已连接 跳过
             *              存在状态  断开 连接
             *             不存在    创建 并连接
             */
            bool isConnect = true;
            string getVpnCommand =
                $" Get-VpnConnection -Name {entryName} -ErrorAction SilentlyContinue";
            string output = RunPowerShellCommand(getVpnCommand);
            if (String.IsNullOrWhiteSpace(output))
            {
                // 不存在 创建
                string command = @$"
            Add-VpnConnection -Name '{entryName}' -ServerAddress '{address}' -TunnelType Automatic -RememberCredential -Force
            rasdial {username} YourUsername {password} ";
                RunPowerShellCommand(command);
            }
            else
            {
                string[] results = output.Trim().Split("\r\n");
                foreach (var item in results)
                {
                    string[] value = item.Split(":");
                    if (value.Length >= 2 && value[0].Contains("ConnectionStatus"))
                    {
                        if (value[1].Contains("Connected"))
                        {
                            isConnect = false;
                            return;
                        }
                    }
                }
            }

            if (isConnect)
            {
                string connectCommand = $" rasdial {entryName} {username} {password}";
                output = RunPowerShellCommand(connectCommand);
            }

            Console.WriteLine("VPN===result：" + output);
        }

        // 运行 PowerShell 命令
        private static String RunPowerShellCommand(string command)
        {
            ProcessStartInfo psi = new ProcessStartInfo("powershell", $"-Command \"{command}\"");
            psi.UseShellExecute = false;
            psi.CreateNoWindow = true;
            psi.RedirectStandardOutput = true;
            psi.Verb = "runas"; // 以管理员权限运行
            using (Process process = Process.Start(psi))
            {
                process.WaitForExit();
                return process.StandardOutput.ReadToEnd();
            }
        }
    }
}